import React, { useState } from 'react';
import { router } from 'expo-router';
import { CameraView, CameraType, useCameraPermissions } from 'expo-camera';
import { WhiteSpace } from '@ant-design/react-native';
import { Text, View, StyleSheet, Modal, TouchableOpacity, Button, TextInput } from 'react-native';
import ButtonDemo from '@/components/features/device/ButtonDemo';
import { CurrentSceneCard } from '@/components/features/device/CurrentSceneCard';
import ProfileEditor from '@/components/features/device/ProfileEditor';
import { createFamily, joinFamily } from '@/api/family';
import FontAwesome from '@expo/vector-icons/FontAwesome';
export default function BlankScreen() { 
    const [profile, setProfile] = useState({ familyName: '' });
    const [modalVisible, setModalVisible] = useState(false);
    const [facing, setFacing] = useState<CameraType>('back');
    const [scanned, setScanned] = useState(false);
    const [permission, requestPermission] = useCameraPermissions();
    const [inviteInput, setInviteInput] = useState('');
    const handleScanPress = async () => {
        if (!permission || !permission.granted) {
            const result = await requestPermission();
            if (result.granted) {
                setScanned(false);
                setModalVisible(true);
            }
        } else {
            setScanned(false);
            setModalVisible(true);
        }
    };

    const handleBarcodeScanned = async ({ data }: { data: string }) => {
        if (scanned) return;
        setScanned(true);
        setModalVisible(false);
        try {
            await joinFamily({ code: data });
            alert('加入成功！');
            router.push('/HomePage');
        } catch (e: any) {
            alert('加入失败: ' + (e.response?.data?.error?.message || e.message));
        }
    };

    return (
        <View style={{ flex: 1, backgroundColor: '#fff' }}>
            <View style={{ alignItems: 'center' }}>
                <CurrentSceneCard
                    image={require('../assets/images/familyBackground.png')}
                    title="新家"
                    desc="开启智能全家之旅"
                    inLoginPage={true}
                />
                <WhiteSpace size='lg' />
                <WhiteSpace size='lg' />
                <WhiteSpace size='lg' />
                <WhiteSpace size='lg' />
                <WhiteSpace size='lg' />
                <WhiteSpace size='lg' />
                <View>
                    <Text style={styles.title}>创建新家</Text>
                    <ProfileEditor
                        fields={['familyName']}
                        initialFamilyName={profile.familyName}
                        onChange={data => setProfile(prev => ({ ...prev, ...data }))}
                    />
                    <ButtonDemo
                        onPress={async () => {
                            try {
                                // const res = await createFamily({ name: profile.familyName });
                                const response = await createFamily({ name: profile.familyName });
                                console.log('Create family response:', response.data);
                                alert('创建成功！');
                                router.push('/HomePage');
                            } catch (e: any) {
                                alert('创建失败: ' + (e.response?.data?.error?.message || e.message));
                            }
                        }}
                        text="创建新家"
                    />
                </View>
                <WhiteSpace size='lg' />
                <WhiteSpace size='lg' />
                <View>
                    <Text style={styles.title}>已有家庭？</Text>
                    <Text style={styles.desc}>扫码加入</Text>
                    <WhiteSpace size='lg' />
                    <ButtonDemo
                        text="扫码加入"
                        onPress={handleScanPress}
                    />
                </View>
            </View>

            {/* 新增：手动输入邀请码加入家庭
            <View style={{ alignItems: 'center', marginTop: 40, marginBottom: 40 }}>
                <Text style={{ fontSize: 18, fontWeight: 'bold', marginBottom: 8 }}>测试：手动输入邀请码加入家庭</Text>
                <TextInput
                    style={{
                        width: 220,
                        height: 40,
                        borderColor: '#ccc',
                        borderWidth: 1,
                        borderRadius: 8,
                        paddingLeft: 12,
                        marginBottom: 12,
                        backgroundColor: '#f9f9f9'
                    }}
                    value={inviteInput}
                    onChangeText={setInviteInput}
                    placeholder="请输入邀请码"
                    placeholderTextColor="#aaa"
                />
                <ButtonDemo
                    text="加入家庭"
                    onPress={async () => {
                        if (!inviteInput) {
                            alert('请输入邀请码');
                            return;
                        }
                        try {
                            await joinFamily({ code: inviteInput });
                            alert('加入成功！');
                            router.push('/HomePage');
                        } catch (e: any) {
                            // alert('加入失败: ' + (e.response?.data?.error?.message || e.message));
                        }
                    }}
                />
            </View> */}

            <Modal
                visible={modalVisible}
                animationType="slide"
                transparent
                onRequestClose={() => setModalVisible(false)}
            >
                <View style={styles.modalContainer}>
                    <View style={styles.sheet}>
                        <Text style={styles.sheetTitle}>扫码加入家庭</Text>
                        {permission && permission.granted ? (
                            <View style={{ width: 250, height: 250, backgroundColor: '#eee', borderRadius: 12, overflow: 'hidden' }}>
                                <CameraView style={styles.camera} facing={facing} onBarcodeScanned={handleBarcodeScanned}>
                                    <View style={styles.buttonContainer} />
                                </CameraView>
                            </View>
                        ) : (
                            <Text>没有摄像头权限</Text>
                        )}
                        <WhiteSpace size='lg' />
                        <View style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 12 }}>
                            <FontAwesome name="qrcode" size={60} color="#000" />
                            <Text style={{ marginLeft: 12, fontSize: 16, color: '#333' }}>扫描用户已有家庭页面的邀请码</Text>
                        </View>
                        <TouchableOpacity onPress={() => setModalVisible(false)} style={styles.closeBtn}>
                            <Text style={{ color: '#3366cc', fontSize: 16 }}>关闭</Text>
                        </TouchableOpacity>
                    </View>
                </View>
            </Modal>
        </View>
    );
}

const styles = StyleSheet.create({
    title: {
        color: '#000',
        fontSize: 24,
        marginTop: 4,
        fontWeight: 'bold',
    },
    desc: {
        color: '#666',
        fontSize: 16,
        marginTop: 10,
    },
    modalContainer: {
        flex: 1,
        justifyContent: 'flex-end',
        backgroundColor: 'rgba(0,0,0,0.3)',
    },
    sheet: {
        backgroundColor: '#fff',
        borderTopLeftRadius: 16,
        borderTopRightRadius: 16,
        padding: 24,
        alignItems: 'center',
    },
    sheetTitle: {
        fontSize: 18,
        fontWeight: 'bold',
        marginBottom: 16,
    },
    closeBtn: {
        marginTop: 24,
    },
    container: {
        flex: 1,
        justifyContent: 'center',
    },
    message: {
        textAlign: 'center',
        paddingBottom: 10,
    },
    camera: {
        flex: 1,
    },
    buttonContainer: {
        flex: 1,
        flexDirection: 'row',
        backgroundColor: 'transparent',
        margin: 64,
    },
    button: {
        flex: 1,
        alignSelf: 'flex-end',
        alignItems: 'center',
    },
    text: {
        fontSize: 24,
        fontWeight: 'bold',
        color: 'white',
    },
});

export const options = {
    headerShown: false,
};
function useEffect(arg0: () => void, arg1: never[]) {
    throw new Error('Function not implemented.');
}

